﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChipTool.Enties;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using XChip_Common;

namespace XChipTool
{
    public partial class XChip_DeriveNew : DevExpress.XtraEditors.XtraUserControl
    {
        public parameter_exportManager Pe_dal { get; set; }

        public parameter_export_sceneManager Pes_dal { get; set; }
        public XChip_DeriveNew()
        {
            InitializeComponent();
        }
        public XChip_DeriveNew(parameter_exportManager _Pe_dal, parameter_export_sceneManager _Pes_dal)
        {
            Pe_dal = _Pe_dal;
            Pes_dal = _Pes_dal;
            InitializeComponent();
        }
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            var row = gridView1.GetSelectedRows();
            var selrow = row[0];
            var _id = gridView1.GetRowCellValue(row[0], "id").ToString();
            var _module = gridView1.GetRowCellValue(row[0], "Module").ToString();
            var _sort = gridView1.GetRowCellValue(row[0], "SortNum").ToString();
            var _addr = gridView1.GetRowCellValue(row[0], "addr").ToString();
            if (e.Button.Caption.Contains("删除"))
            {
                Pe_dal.Delete(c=>c.id ==int.Parse(_id));
            }
            else if (e.Button.Caption.Contains("新增"))
            {
                XChip_DeriveAdd xda = new XChip_DeriveAdd(int.Parse(_id));
                xda.SendDeriveAdd += Xda_SendDeriveAdd;
                xda.ShowDialog();
            }
            else if (e.Button.Caption.Contains("上移"))
            {
                List<parameter_export> list = new List<parameter_export>();
                try
                {
                    list = Pe_dal.GetList(c => c.Module == _module).OrderBy(c => c.SortNum).ToList();
                }
                catch
                {
                    list = Pe_dal.GetList().OrderBy(c => c.SortNum).ToList();
                }
                var minNo = list.Min(c => c.SortNum);
                if (_sort == minNo.ToString())
                {
                    return;
                }
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Module == _module && _addr == list[i].addr && (i - 1 >= 0))
                    {
                        var temp = -1;
                        if (list[i - 1].SortNum != list[i].SortNum)
                        {
                            temp = list[i - 1].SortNum;
                            list[i - 1].SortNum = list[i].SortNum;
                        }

                        list[i].SortNum = temp;
                    }
                }
                Pe_dal.Update(list);
                selrow = selrow - 1;
                //row = row[0] - 1;
            }
            else if (e.Button.Caption.Contains("下移"))
            {
                List<parameter_export> list = new List<parameter_export>();
                try
                {
                    list = Pe_dal.GetList(c => c.Module == _module).OrderBy(c => c.SortNum).ToList();
                }
                catch
                {
                    list = Pe_dal.GetList().OrderBy(c => c.SortNum).ToList();
                }
                var maxNo = list.Max(c => c.SortNum);
                if (_sort == maxNo.ToString())
                {
                    return;
                }
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Module == _module && _addr == list[i].addr && (i + 1 <= list.Count))
                    {
                        var temp = -1;
                        if (list[i + 1].SortNum != list[i].SortNum)
                        {
                            temp = list[i + 1].SortNum;
                            list[i + 1].SortNum = list[i].SortNum;
                        }
                        list[i].SortNum = temp;
                    }
                }
                Pe_dal.Update(list);
                selrow = selrow + 1;
            }
            gridControl1.DataSource = Pe_dal.GetList().OrderBy(c => c.SortNum).ToList();
            gridView1.RefreshData();
            gridView1.FocusedRowHandle = selrow;

        }
        /// <summary>
        /// 刷新表格三
        /// </summary>
        private void Xda_SendDeriveAdd()
        {
            //gridView3_RowCellClick(null, null);
        }

        private void XChip_DeriveNew_Load(object sender, EventArgs e)
        {
            if (null != Pe_dal)
            {
                var peList = Pe_dal.GetListToExport("ALL");
                gridControl1.DataSource = peList;
                gridView1.RefreshData();
                var sheetList = peList.Select(c => c.PidM).Distinct().ToList();
                foreach (var item in sheetList)
                {
                    comboBoxEdit1.Properties.Items.Add(item);
                }
            }
        }
        /// <summary>
        /// 选择框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var peList = Pe_dal.GetListToExport("ALL");
            gridControl1.DataSource = peList.Where(c=>c.PidM == comboBoxEdit1.SelectedText);
            gridView1.RefreshData();
          
        }
        
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton7_Click(object sender, EventArgs e)
        {
          //  parameter_export_sceneManager pesDal = new parameter_export_sceneManager();
            parameter_exportManager peDal = new parameter_exportManager();
          //  var pesList = pesDal.GetList();
            var peList = peDal.GetListToExport("ALL");
            var sheetList = peList.Select(c => c.PidM).Distinct().ToList();
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "导出文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "模板_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                foreach (var sheetitem in sheetList)
                {
                    //var list = pesList.Where(c => c.Name == sheetitem).OrderBy(c=>c.Sort).Select(c=>c.Module).ToList();
                    var pList = peList.Where(c => c.PidM == sheetitem).OrderBy(c=>c.SortNum).ToList();
                    DataTable dt = NPOIOprateExcel.ListToDataTable(pList);
                    dt.Columns.Remove("id");
                    dt.Columns.Remove("SortNum");
                    dt.Columns.Remove("PidM");
                    dt.Columns.Remove("RelationAddr");
                    dt.Columns.Remove("ConditionAddr");
                    dt.Columns.Remove("Bit");
                    dt.Columns.Remove("Val");

                    createSheet(dt, true, workbook, sheetitem);
                }
                FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                workbook.Write(fs);
                fs.Close();
            }
            DevExpress.XtraEditors.XtraMessageBox.Show($"导出完成！");
        }
        private ISheet createSheet(DataTable data, bool isColumnWritten, HSSFWorkbook workBook, string sheetName)
        {

            int count = 0;
            ISheet sheet = workBook.CreateSheet(sheetName);
            if (isColumnWritten == true) //写入DataTable的列名
            {
                IRow row = sheet.CreateRow(0);
                for (int j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                }
                count = 1;
            }
            else
            {
                count = 0;
            }
            for (int i = 0; i < data.Rows.Count; ++i)
            {
                IRow row = sheet.CreateRow(count);
                for (int j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                }
                ++count;
            }
            
            return sheet;
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var fs = new FileStream(sfd.FileName, FileMode.Open, FileAccess.Read);
                    var workbook = new HSSFWorkbook(fs);
                    parameter_export_sceneManager pesDal = new parameter_export_sceneManager();
                    parameter_exportManager peDal = new parameter_exportManager();
                   
                    int SortNum = 0;
                    var SList =  NPOIOprateExcel.GetSheetName(workbook);
                  
                    int sort = 0;
                    for (int i = 0; i < SList.Count; i++)
                    {
                        List<parameter_export_scene> pesAll = new List<parameter_export_scene>();
                        var sheetid = workbook.GetSheetIndex(SList[i]);
                        DataTable dt = NPOIOprateExcel.ExcelToDataTable(sfd.FileName, true, sheetid);
                        List<parameter_export> peList = dt.ToList<parameter_export>().ToList();
                        var pesTList = peList.Select(c => c.Module).Distinct().ToList();
                        for (int j  = 0; j < pesTList.Count(); j++)
                        {
                            parameter_export_scene model = new parameter_export_scene();
                            model.pid = 10;
                            model.Name = SList[i];
                            model.Module = pesTList[j];
                            model.Sort = sort;
                            pesAll.Add(model);
                            peDal.Delete(c => c.Module == pesTList[j]);
                            sort++;
                        }
                        pesDal.Delete(c => c.Name == SList[i]);
                        pesDal.Insert(pesAll);
                       
                        for (int j = 0; j < peList.Count; j++)
                        {
                            peList[j].SortNum = SortNum++;
                        }
                        peDal.Insert(peList);
                    }
                   
                    DevExpress.XtraEditors.XtraMessageBox.Show($"导入完成！");
                }
                catch (Exception ex)
                {

                    DevExpress.XtraEditors.XtraMessageBox.Show($"打开表格错误信息：{ex.Message.ToString()}");
                }
            }
        }
    }
}
